<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;

use app\common\logic\Article as CommonArticle;
use app\common\model\ArticleCategory;
use app\common\model\GamblerKing;
use app\common\model\Member;
use app\common\model\Picture;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use think\Db;

/**
 * 文章接口逻辑
 */
class Article extends ApiBase
{
    
    public static $commonArticleLogic = null;
    
    /**
     * 基类初始化
     */
    public function __construct()
    {
        // 执行父类构造方法
        parent::__construct();
        
        empty(static::$commonArticleLogic) && static::$commonArticleLogic = get_sington_object('Article', CommonArticle::class);
    }
    
    /**
     * 获取赌王列表
     */
    public function kinglist($data)
    {

        $where=['state'=>2,'status'=>1];
        !empty($data['search']) && $where['name|describe|content']=['like','%'.$data['search'].'%'];
        !empty($data['cate_id']) && $where['cates']=['like',','.$data['cate_id'].','];

        $king_list=$this->modelGamblerKing->where(['state'=>2,'status'=>1])->order('profit desc')->column('id');
        $king_arr=[];
        foreach ($king_list as $k=>$v){
            $king_arr[$v]=$k+1;
        }

        $list=$this->modelGamblerKing->getList($where,'id,user_id,name,sex,winning_rate,fail_rate,tags,help_number,cover_id,credit_score','profit desc');
        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->image;
            $list[$k]['investment_count']=$v->investment_count;
            $list[$k]['tags_arr']=explode(',',$v->tags_name);
            $list[$k]['ranking_number']=$king_arr[$v['id']];
        }
        return $list;

    }

    /**
     * 获取活动列表
     */
    public function activelist($data)
    {


        $where=[];
        if(!empty($data['search'])){
            $where['name|content']=['like','%'.$data['search'].'%'];
        }

        $list=$this->modelActive->getList($where,'id,cover_id,address,name,time,create_time','create_time desc');


        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->image;
        }


        return $list;

    }



    /**
     * 获取文章列表
     */
    public function getArticleList($data)
    {
        $where=[];
        $uid=$this->logicApiBase->member['id'];
        if(!empty($data['search'])){
            $where['name|describe|content']=['like','%'.$data['search'].'%'];
        }
        if(!empty($data['category_id'])){
            $where['category_id']=$data['category_id'];
        }
        if(!empty($data['tag_id'])){
            $where['level']=$data['tag_id'];
        }
        $list=$this->modelArticle->getList($where,'id,cover_id,describe,play_count,video_cate_id,name,content,video_type,file_id,video_url,create_time','create_time desc');


        foreach ($list as $k=>$v){
            $list[$k]['image']=$v->image;
            $list[$k]['video']=$v->video;
            if($v->video){
                $list[$k]['video_cate']=$v->videocate->data['name'];
                $list[$k]['video_image']=$v->videocate->image;
                unset($v->videocate);
            }else{
                $list[$k]['video_cate']='';
                $list[$k]['video_image']='';
            }
            $list[$k]['play_count']=arrangement_total($v['play_count']);

            $list[$k]['is_fabulous']=Db::name('article_fabulous_log')->where(['article_id'=>$v['id'],'user_id'=>$uid])->count();
            $list[$k]['fabulous_type']=Db::name('article_fabulous_log')->where(['article_id'=>$v['id'],'user_id'=>$uid])->value('type');
            $list[$k]['add_time']=date('Y-m-d',$v['create_time']);

        }


        return $list;
    }


    /***
     * 文章点赞
     */

    public function article_fabulous($data){
        $uid=$this->logicApiBase->member['id'];
        $info=$this->modelArticle->getInfo(['id'=>$data['id']]);
        if(!$info){
            return ajaxreturn(1,lang('文章不存在'));
        }
        if($data['type']!=1 && $data['type']!=2){
            return ajaxreturn(1,lang('参数错误'));
        }
        $log=Db::name('article_fabulous_log')->where(['article_id'=>$info['id'],'user_id'=>$uid])->count();

            if($log){
                Db::name('article_fabulous_log')->where(['article_id'=>$info['id'],'user_id'=>$uid])->update(['type'=>$data['type']]);
            }else {
                Db::name('article_fabulous_log')->insert([
                    'user_id'=>$uid,
                    'article_id'=>$info['id'],
                    'create_time'=>TIME_NOW,
                    'type'=>$data['type']
                ]);

            }

        return ajaxreturn(0,lang('操作成功'));


    }



    
    /**
     * 获取文章信息
     */
    public function getArticleInfo($data = [])
    {
        
        $info= static::$commonArticleLogic->getArticleInfo(['a.id' => $data['article_id']], 'a.name,a.play_count,a.category_id,video_type,video_url,a.id,a.describe,file_id,a.content,a.cover_id,m.nickname,c.name as category_name');
       $info->image;
       $info->video;
        $info['play_count']+=1;
        $info->save();
        return $info;
    }

    /**
     * 获取活动
     */
    public function getActiveInfo($data = [])
    {

        $info= $this->modelActive->getInfo(['id' => $data['id']]);
//        $info['guest']=$info->getKing();
//        $info->ticket;
        return $info;
    }

    /**
     * 活动报名页面
     */
    public function getActiveInfoJion($data = [])
    {

        $info= $this->modelActive->getInfo(['id' => $data['id']]);
        $info['guest']=$info->getKing();
        $info->ticket;
        return $info;
    }


    /**
     * 购买门票
     */
    public function buy_ticket($data){
        $uid=decoded_user_token($data['user_token'],'member_id');

        $validate_result = $this->validateTicket->scene('buy_ticket')->check($data);

        if (!$validate_result) {

            return ajaxreturn(1,lang($this->validateTicket->getError()));
        }

//        $mymember=Member::get($uid);
//        if($mymember['pin_password']!=md5($data['pin_password'].'pin')){
//            return ajaxreturn(1,lang('PIN密码不正确'));
//        }

        $ticket=$this->modelActiveTicket->getInfo(['id'=>$data['ticket_id']]);
        if(!$ticket){
            return ajaxreturn(1,lang('参数错误'));
        }
        $data['number']=$ticket['price'];




        Db::startTrans();
        $account=UserAccount::check(['wallet_id'=>3,'user_id'=>$uid],false);
        if($data['number']>$account['balance']){
            return ajaxreturn(1,lang('理财包余额不足'));
        }
        try{
            //扣除用户钱包余额
            $account->balance-=$data['number'];
            $account->save();

            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$uid,
                'number'=>$data['number'],
                'wallet_id'=>3,
                'before_blance'=>$account->balance+$data['number'],
                'after_blance'=>$account->balance,
                'is_add'=>2,
                'type'=>4
            ]);



            //写入购买记录
            $data['user_id']=$uid;
            $data['form_wallet_id']=3;
            $data['type']=5;
            $data['state']=1;
            $result=$this->modelTransfer->setInfo($data);

            //插入票据表
            $this->modelUserTicket->setInfo([
                'user_id'=>$uid,
                'ticket_id'=>$data['ticket_id'],
                'transfer_id'=>$result,
                'full_name'=>$data['full_name'],
                'sex'=>$data['sex'],
                'mobile'=>$data['mobile'],
                'email'=>$data['email']
            ]);
            Db::commit();

            return ajaxreturn(0,lang('购买成功'));
        }catch (\Exception $e){
            Db::rollback();
            //return ajaxreturn(0,$e->getMessage());
            return ajaxreturn(1,lang('服务器繁忙,请稍后再试'));
        }


    }

    /***
     * @param $data
     * @return mixed
     */
    public  function  full_list($data){
        $where=$where1=$where2=[];
        if(!empty($data['search'])){
            $where['name|describe|content']=['like','%'.$data['search'].'%'];
            $where1['name|content']=['like','%'.$data['search'].'%'];
            $where2['a.name|a.describe|a.content']=['like','%'.$data['search'].'%'];

            $king_list=$this->modelGamblerKing->getList($where,'id,cover_id,tags,name,winning_rate,fail_rate','create_time desc',false);

            foreach ($king_list as $k=>$v){
                $king_list[$k]['image']=$v->image;
                $king_list[$k]['tags_name']=$v->tags_name;
                $king_list[$k]['article_type']=1;

            }
        }



        $active_list=$this->modelActive->getList($where1,'id,cover_id,address,name,time,create_time','create_time desc',false);

        foreach ($active_list as $k=>$v){
            $active_list[$k]['image']=$v->image;
            $active_list[$k]['article_type']=2;
        }
        $where2['c.type']=1;
        $this->modelArticle->alias('a');

        $join = [
            [SYS_DB_PREFIX . 'article_category c', 'a.category_id = c.id'],
        ];
        $this->modelArticle->join = $join;
        $news_list=$this->modelArticle->getList($where2,'a.id,a.cover_id,a.describe,a.name,a.content,video_type,file_id,video_url,a.create_time','a.sort desc,a.id desc',false);

        foreach ($news_list as $k=>$v){
            $news_list[$k]['image']=$v->image;
            $news_list[$k]['video']=$v->video;
            $news_list[$k]['add_time']=date('Y-m-d',$v['create_time']);
            $news_list[$k]['article_type']=3;

        }
        if(!empty($data['search'])){
            $list=array_merge($king_list,$active_list,$news_list);
        }else{
            $list=array_merge($active_list,$news_list);
        }

//        $arr1=array_column($list,'create_time');
//        array_multisort($arr1,SORT_DESC,$list);
        $page=empty($data['page'])?1:$data['page'];
        $pagesize= empty($data['list_rows'])?10:$data['list_rows'];
        $count = count($list);//总条数
        $start=($page-1)*$pagesize;//偏移量，当前页-1乘以每页显示条数
        $list = array_slice($list,$start,$pagesize);
     //   dd($list);

        return ['total'=>$count,'per_page'=>$pagesize,'current_page'=>$page,'last_page'=>ceil($count/$pagesize),'data'=>$list];

    }



    /***
     * @param $data
     * @return mixed
     */
    public  function  hot_list(){
        $where=$where1=$where2=['is_hot'=>1];

        $king_list=$this->modelGamblerKing->getList($where,'id,name,sort','create_time desc',false);

        foreach ($king_list as $k=>$v){
            $king_list[$k]['article_type']=1;

        }

        $active_list=$this->modelActive->getList($where1,'id,name,sort','create_time desc',false);

        foreach ($active_list as $k=>$v){

            $active_list[$k]['article_type']=2;
        }

        $news_list=$this->modelArticle->getList($where2,'id,name,sort','create_time desc',false);

        foreach ($news_list as $k=>$v){
            $news_list[$k]['article_type']=3;

        }

        $list=array_merge($king_list,$active_list,$news_list);
        $arr1=array_column($list,'sort');
        array_multisort($arr1,SORT_DESC,$list);
        $list=array_slice($list,0,8);
        return $list;

    }


    /***
     * 资讯首页
     */
    public function  news_index(){
        $cate=ArticleCategory::field('id,name')->where(['status'=>1,'type'=>1])->select();
        $arr=[
            [ 'id'=>'active','name'=>lang('赌场活动')],

        ];
        $cate_list=array_merge($arr,$cate);
      //  dd($cate_list);
        foreach ($cate_list as $k =>$v){
            switch($v['id']){
                case 'active':
                    $list=$this->modelActive->field('id,content,cover_id,address,time')->where(['status'=>1])->limit(3)->order('create_time desc')->select();
                    foreach ($list as $ke=>$va){
                        $list[$ke]['image']=$va->image;
                    }
                    break;
                default:
                    $list=$this->modelArticle->alias('a')->join('__ARTICLE_CATEGORY__ c','a.category_id = c.id')->field('a.id,a.content,a.name,a.cover_id,a.describe,a.content,a.video_url,video_type,a.create_time')->where(['a.status'=>1,'a.category_id'=>$v['id'],'c.type'=>1,'level'=>0])->limit(3)->order('a.sort desc,a.id desc')->select();
                    foreach ($list as $ke=>$va){
                        $list[$ke]['image']=$va->image;
                        $list[$ke]['video']=$va->video;
                        $list[$ke]['add_time']=date('Y-m-d',$va['create_time']);

                    }
                    break;
            }
            $cate_list [$k]['list']=$list;
        }

        return $cate_list;
    }


    /***
    * 换一批
    */
    public function  next_list($data){


        $list=$this->modelArticle->alias('a')->field('a.id,a.content,a.cover_id,a.describe,a.content,a.video_url,video_type,a.create_time,file_id')->join('__ARTICLE_CATEGORY__ c','a.category_id = c.id')->where(['a.status'=>1,'a.category_id'=>$data['category_id'],'c.type'=>1])->order('a.sort desc,a.id desc')->select();
        if(count($list)>3){
            $arr=array_rand($list,3);
            $ar=[];
            foreach ($arr as $ke=>$va){
                $list[$ke]['video']=$list[$va]->video;
                $list[$ke]['add_time']=date('Y-m-d',$list[$va]['create_time']);
                $list[$va]['image']=$list[$va]->image;
                $ar[]=$list[$va];
            }
            return $ar;
        }else{
            foreach ($list as $ke=>$va){
                $list[$ke]['video']=$va->video;
                $list[$ke]['add_time']=date('Y-m-d',$va['create_time']);
                $list[$ke]['image']=$va->image;
            }
            return $list;
        }


    }





}
